package com.example.interceptor;

import com.example.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("拦截器开始！！！");
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //配置jwt，生成token 暂时未实现
        String token = request.getHeader("token");
        if(token == null){
            return false;
        } else if (token != null) {
            token = token.trim().replaceAll("^\"|\"$", "");
        }
        System.out.println("拦截器 拦截到的 token:"+token);
        Boolean validate = JwtUtil.validate(token);
        if (validate) {
            return true;
        }else {
            return false;
        }

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                          Object handler, Exception ex) throws Exception {
        System.out.println("postHandle");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                               Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }

}
